import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { AdminApiService } from './../../api/admin-api.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.less', '../login/login.component.less']
})
export class RegisterComponent implements OnInit {

  registerForm: FormGroup;
  constructor(
    private fb: FormBuilder,
    private adminApi: AdminApiService,
    private msg: NzMessageService,
    private modal: NzModalService,
    private router: Router
  ) {
    this.registerForm = this.fb.group({
      // TODO: 加入, [this.userNameAsyncValidator]
      userName: ['', [Validators.required]],
      password: ['', [Validators.required]],
      confirm: ['', [this.confirmValidator]]
    });
  }

  ngOnInit(): void {
  }

  submitForm(): void {
    for (const key in this.registerForm.controls) {
      this.registerForm.controls[key].markAsDirty();
      this.registerForm.controls[key].updateValueAndValidity();
    }
    if (this.registerForm.valid) {
      const username = this.registerForm.controls.userName.value;
      const password = this.registerForm.controls.password.value;
      this.adminApi.register(username, password).subscribe(
        user => {
          this.modal.confirm({
            nzTitle: '注册成功',
            nzContent: '用户' + user.name + '注册成功，点击确认转至登录页',
            nzOnOk: () => { this.router.navigateByUrl('/login'); },
          });

        },
        err => {
          this.msg.error('注册错误');
          console.error(err);
        }
      );
    }

  }

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.registerForm.reset();
    for (const key in this.registerForm.controls) {
      this.registerForm.controls[key].markAsPristine();
      this.registerForm.controls[key].updateValueAndValidity();
    }
  }

  validateConfirmPassword(): void {
    setTimeout(() => this.registerForm.controls.confirm.updateValueAndValidity());
  }

  confirmValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { error: true, required: true };
    } else if (control.value !== this.registerForm.controls.password.value) {
      return { confirm: true, error: true };
    }
    return {};
  }

  userNameAsyncValidator = (control: FormControl) => {
    return {};
  }

}
